import Vue from 'vue';
import FontSizeManager from './fontSizeManager.js';

// px 转换为 rem
export const pxtorem = (px = 0, rootValue = 37.5) => {

  const manager = FontSizeManager.getInstance();
  if (manager) {
    rootValue = manager.getRootFontSize();
    // console.log('Root font-size from manager:', rootValue);
  }

  if (typeof px === 'string') {
    px = parseFloat(px);
  }
  return px / rootValue + 'rem';
};

// 动态计算字体大小
const canvas = document.createElement('canvas'); // 复用 canvas 元素
const context = canvas.getContext('2d');

const calcFontSize = (text, width, baseFontSize = 17, minFontSize = 8, maxFontSize = 16) => {
  if (!text || width <= 0) return baseFontSize; // 边界检查
  context.font = `${baseFontSize}px -apple-system, BlinkMacSystemFont,"Segoe UI","HarmonyOS Sans","Roboto","PingFang SC",sans-serif`;
  const textWidth = context.measureText(text).width;
  let newFontSize = Math.max(minFontSize, Math.min(maxFontSize, Math.floor((baseFontSize * width) / textWidth)));
  
  // 额外检查：如果计算出的字体大小仍然导致溢出，则进一步减小
  context.font = `${newFontSize}px -apple-system, BlinkMacSystemFont,"Segoe UI","HarmonyOS Sans","Roboto","PingFang SC",sans-serif`;
  // 确保容器的宽度比文字的宽度大0.5 以上，用于兼容比较接近的边界值，避免浮点数问题导致的显示不全
  while (context.measureText(text).width > width - 0.5 && newFontSize > minFontSize) {
    newFontSize -= 1;
    context.font = `${newFontSize}px -apple-system, BlinkMacSystemFont,"Segoe UI","HarmonyOS Sans","Roboto","PingFang SC",sans-serif`;
  }
  console.log('Calculated font size');
   // 获取字体管理类, 缓存获取字号信息
  const manager = FontSizeManager.getInstance();
  manager.updateFontCache(String(text) + width, newFontSize);
  return newFontSize;
};

// 自定义指令
const directives = {
  bind(el, binding) {
    const defaultConfig = {
      baseFontSize: 17,
      minFontSize: 8,
      maxFontSize: 16,
    };

    let config = { ...defaultConfig };
    if (typeof binding.value === 'object' && binding.value !== null) {
      config = { ...config, ...binding.value };
    } else if (typeof binding.value === 'number') {
      config.baseFontSize = binding.value;
    }

    el.__autoFontSize__ = () => {
      if (el.innerText && el.clientWidth > 0) {
          // 获取字体管理类, 优先缓存获取字号信息
          const manager = FontSizeManager.getInstance();
          let finalFontSize = manager.getFontCache(String(el.innerText) + el.clientWidth);
          if(!finalFontSize) {
             finalFontSize = calcFontSize(el.innerText, el.clientWidth, config.baseFontSize, config.minFontSize, config.maxFontSize);
          }
          el.style.fontSize = pxtorem(finalFontSize);
      }
    };

    window.addEventListener('resize', el.__autoFontSize__);
    el.__autoFontSize__();
  },

  inserted(el) {
    if (el.innerText && el.clientWidth > 0) {
      el.__autoFontSize__?.();
    }
  },

  update(el) {
    Vue.nextTick(() => {
      if (el.innerText && el.clientWidth > 0) {
        el.__autoFontSize__?.();
      }
    });
  },

  unbind(el) {
    window.removeEventListener('resize', el.__autoFontSize__);
    delete el.__autoFontSize__;
  },
};

export default directives;